import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { StorageService } from './StorageService';
import { UserInfoData } from '../model/UserInfoData';

@Injectable()
export class HttpService {
  local: Storage;
  API_URL: string;
  constructor(
    private http: Http,
    private storageService: StorageService
  ) {
    //this.API_URL = 'https://rent.egodao.com';
    this.API_URL = '';
  }

  public httpGetWithAuth(url: string) {
    let user = this.storageService.read<UserInfoData>('UserInfo');
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization', user.ID + '-' + user.UserToken);
    let options = new RequestOptions({ headers: headers });
    return this.http.get(url, options).toPromise()
      .then(res => res.json())
      .catch(err => {
        this.handleError(err);
      });
  }
  public httpGetNoAuth(url: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers });
    return this.http.get(url, options).toPromise()
      .then(res => res.json())
      .catch(err => {
        this.handleError(err);
      });
  }
  public httpPostNoAuth(url: string, body: any) {
    url = this.API_URL + url;
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers });
    return this.http.post(url, body, options).toPromise()
      .then(res => res.json())
      .catch(err => {
        this.handleError(err);
      });
  }
  private handleError(error: Response) {
    //console.log(error);
    //return Observable.throw(error.json().error || 'Server Error');
  }
}
